import 'package:flutter/material.dart';
import 'package:shenling_flutter/pages/home/home_page.dart';
import 'package:shenling_flutter/pages/message/message.dart';
import 'package:shenling_flutter/pages/mine/minePage.dart';
import 'package:shenling_flutter/utils/auth.dart';
import 'package:shenling_flutter/utils/event_bus.dart';

class Tabbar extends StatefulWidget {
  const Tabbar({super.key});

  @override
  State<Tabbar> createState() => _TabbarState();
}

class _TabbarState extends State<Tabbar> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  //定义初始下标
  int _index = 0;
  @override
  void initState() {
    super.initState();
    //创建tab数量对应的控制器
    _tabController = TabController(length: 3, vsync: this);
    //监听下标变换
    _tabController.addListener(_handleChange);
    //初始化token
    Future.delayed(Duration.zero, () async {
      await Auth().init();
    });
    // // 接收传递过来的事件及参数
    // eventBus.on<getHomeEvent>().listen((event) {
    //   setState(() {
    //     _tabController.index = event.index;
    //     _index = _tabController.index;
    //   });
    // });
    // 401时退出登录
    eventBus.on<LogoutEvent>().listen((event) {
      Navigator.pushNamed(context, '/login');
    });
  }

  _handleChange() {
    if (_tabController.indexIsChanging) {
      setState(() {
        _index = _tabController.index;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TabBarView(
          controller: _tabController,
          // 禁止滑动
          physics: const NeverScrollableScrollPhysics(),
          //tab 内容
          children: const [HomePage(), MessagePage(), Minepage()]),
      // 底部导航栏
      bottomNavigationBar: Material(
        // 添加 Material 组件以确保底部导航栏有正确的背景色
        color: Colors.white,
        child: TabBar(
          controller: _tabController,
          labelColor: Colors.red,
          unselectedLabelColor: Colors.grey,
          indicatorColor: Colors.transparent,
          tabs: [
            Tab(
              icon: Image.asset(
                'assets/imgs/task.png',
                width: 24,
                height: 24,
                color: _index == 0 ? Colors.red : Colors.grey,
              ),
              text: '任务',
            ),
            Tab(
              icon: Image.asset(
                'assets/imgs/msg.png',
                width: 24,
                height: 24,
                color: _index == 1 ? Colors.red : Colors.grey,
              ),
              text: '消息',
            ),
            Tab(
              icon: Image.asset(
                'assets/imgs/mine.png',
                width: 24,
                height: 24,
                color: _index == 2 ? Colors.red : Colors.grey,
              ),
              text: '我的',
            )
          ],
        ),
      ),
    );
  }
}
